<template>
  <div class="app-container">
    <div class="top">
      <div class="operate">
        <el-button
          v-hasPermi="['exceptionMgmt:rule:add']"
          type="primary"
          size="small"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          size="small"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['exceptionMgmt:rule:export']"
          >导出
        </el-button>
        <!-- <el-button
          icon="el-icon-edit"
          size="mini"
          :disabled="single != true"
          @click="handleUpdate()"
          v-hasPermi="['exceptionMgmt:rule:edit']"
          >编辑
        </el-button> -->
        <!-- <el-button
          icon="el-icon-delete"
          size="mini"
          :disabled="single != true && single != false"
          @click="handleDelete()"
          v-hasPermi="['exceptionMgmt:rule:remove']"
          >删除
        </el-button> -->
      </div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item prop="searchValue">
          <el-input
            v-model="queryParams.searchValue"
            placeholder="请输入关键字"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <organizationCascader
            :clearData="clearData"
            :arrData="queryParams"
            :isAllList="true"
            @change="queryParamsChange"
          ></organizationCascader>
        </el-form-item>

        <el-form-item prop="status" class='width-130'>
          <el-select
            placeholder="请选择状态"
            clearable
            v-model="queryParams.status"
            size="small"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="Table"
      :data="list"
      tooltip-effect="dark"
      style="width: 100%"
      height="calc(100% - 55px - 50px)"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="规则编码">
        <template slot-scope="{ row }">
          <el-button type="text" @click.stop="handleLook(row)">{{row.ruleNo}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="关联指标" prop='indexName'></el-table-column>
      <el-table-column label="指标类型">
        <template slot-scope="{ row }">
          <span>{{row.indexType && indexTypeDictMap[row.indexType]}}</span>
        </template>
      </el-table-column>
      <el-table-column label="工厂" prop='factoryDeptName'></el-table-column>
      <el-table-column label="车间" prop='workshopName'></el-table-column>
      <el-table-column label="产线" prop='lineName'></el-table-column>
      <el-table-column label="关联设备" prop='equipmentName'></el-table-column>
      <el-table-column label="责任人">
        <template slot-scope="{ row }">
          <span v-if='row.processedName'>{{row.processedName}}</span>
          <span v-if='row.workStationName'>{{row.workStationName}}</span>
          <span v-if='row.processedCodeName'>{{row.processedCodeName}}</span>
        </template>
      </el-table-column>

      <el-table-column label="异常区间">
        <template slot-scope="{ row }">
          <template v-if='(row.abnormalMin == null || row.abnormalMin == undefined || row.abnormalMin === "") && row.abnormalMax != null && row.abnormalMax != undefined && row.abnormalMax !== ""'>
            <span>≤{{row.abnormalMax}}</span>
          </template>
          <template v-else-if='(row.abnormalMax == null || row.abnormalMax == undefined || row.abnormalMax === "") && row.abnormalMin != null && row.abnormalMin != undefined && row.abnormalMin !== ""'>
            <span>≥{{row.abnormalMin}}</span>
          </template>
          <template v-else>
            {{row.abnormalMin}} - {{row.abnormalMax}}
          </template>
          <span v-if='row.abnormalUnit && row.abnormalUnit != "无"'>{{row.abnormalUnit}}</span>
        </template>
      </el-table-column>

      <el-table-column label="预警区间">
        <template slot-scope="{ row }">
          <template v-if='(row.warmMin == null || row.warmMin == undefined || row.warmMin === "") && (row.warmMax == null || row.warmMax == undefined || row.warmMax === "")'>
            <span>-</span>
          </template>

          <template v-else>
            <span v-if='(row.warmMin == null || row.warmMin == undefined || row.warmMin === "") && row.warmMax != null && row.warmMax != undefined && row.warmMax !== ""'>
              <span>≤{{row.warmMax}}</span>
            </span>
            <span v-else-if='(row.warmMax == null || row.warmMax == undefined || row.warmMax === "") && row.warmMin != null && row.warmMin != undefined && row.warmMin !== ""'>
              <span>≥{{row.warmMin}}</span>
            </span>
            <span v-else>
              {{row.warmMin}} ~ {{row.warmMax}}
            </span>
            <span v-if='row.warmUnit && row.warmUnit != "无"'>{{row.warmUnit}}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="状态">
        <template slot-scope="{ row }">
          <!-- 0，生效中；1，已停用; 9,已删除 -->
          <span v-if='row.status == 1' class="status-use">已停用</span>
          <span v-else class="status-stop">生效中</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="{row}">
          <template v-if='row.status == 1'>
            <el-button v-hasPermi="['exceptionMgmt:rule:edit']" type="text" @click.stop="handleUpdate(row)">编辑</el-button>
            <el-button v-hasPermi="['exceptionMgmt:rule:remove']" type="text" @click.stop="handleDelete(row)">删除</el-button>
            <el-button v-hasPermi="['exceptionMgmt:rule:stop']" type="text" @click.stop="handleOperate(row,'0')">启用</el-button>
          </template>

          <template v-if='row.status == 0'>
            <el-button v-hasPermi="['exceptionMgmt:rule:start']" type="text" @click.stop="handleOperate(row,'1')">停用</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pager.total"
      :page.sync="pager.pageNum"
      :limit.sync="pager.pageSize"
      @pagination="getList"
    />
    <DetailDialog
      :visible.sync="detailDialog.visible"
      :row="detailDialog.row"
      :mode="detailDialog.mode"
      :title="detailDialog.title"
      @submit-success="getList">
    </DetailDialog>
  </div>
</template>
<script>
import { ruleList,delErpFormula,statusErpFormula, exportRule } from "@/api/exceptionMgmt/rule";
import organizationCascader from "@/views/components/organizationCascader";
import DetailDialog from "./detailDialog";
import { mapState,mapGetters, mapMutations,mapActions } from "vuex";
import { downloadFile } from "@/utils/file";
export default {
  components: {organizationCascader,DetailDialog },
  name:"Rule",
  data() {
    return {
      queryParams: {
        factoryDeptCode: null,
        workshopCode: null,
        erpProductionLineCode: null,
        lineId:null,
        status:null,
        searchValue:null
      },
      single: null,
      list: [],
      loading: false,
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      clearData:{
        factory:true,
        workshop:true,
        line:true
      },
      detailDialog: {
        visible: false,
        row:{},
        mode:null,
        title:null
      },
      statusList:[
        {value:"0",label:"生效中"},
        {value:"1",label:"已停用"}
      ],
      exportLoading: false
    };
  },
  created() {
    const result = this.getOwnFirstLine()
    this.queryParams.factoryDeptCode = result[0]?.factoryDeptCode;
    this.queryParams.workshopCode = result[1]?.workshopCode;
    this.queryParams.erpProductionLineCode = result[2]?.lineCode;
    this.queryParams.lineId = result[2]?.lineId;
    this.getList();
  },

  computed: {
    ...mapState({
      indexTypeDict: (state) => state.dict.dict.indexType,
    }),
    ...mapGetters([
      'permitList',
      'allList'
    ]),
    indexTypeDictMap() {
      return this.dictToMap(this.indexTypeDict);
    }
  },

  methods: {
    getList() {
      this.loading = true;
      this.single = null;
      const { pageNum, pageSize } = this.pager;
      const param = {
        query:{...this.queryParams},
        pageNum,
        pageSize,
      };
      ruleList(param)
        .then((res) => {
          this.list = res?.rows || [];
          this.pager.total = res?.total || 0;
          this.loading = false;
        })
        .catch(() => {
          this.list = [];
          this.pager.total = 0;
          this.loading = false;
        });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.detailDialog.row = null;
      this.detailDialog.mode = "add";
      this.detailDialog.title = "新增异常规则";
      this.detailDialog.visible = true;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row) {
        row = this.$refs.Table.selection[0] || null
      }
      this.detailDialog.row = row;
      this.detailDialog.mode = "edit";
      this.detailDialog.title = "编辑异常规则";
      this.detailDialog.visible = true;
    },

    //查看
    handleLook(row){
      this.detailDialog.row = row;
      this.detailDialog.mode = "look";
      this.detailDialog.title = "异常规则详情";
      this.detailDialog.visible = true;
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = ''
      if (row) {
        ids = row.id
      } else {
        ids = this.$refs.Table.selection
          .map(ele => ele.id).join(',')
      }
      this.$confirm('是否确认删除所选异常规则?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(() => {
        return statusErpFormula({id:row.id,status:"9"})
      }).then(() => {
         this.getList()
      }).catch(err=>{

      })
    },

    /** 停用启用操作 */
    handleOperate(row,status) {
      let ids = ''
      if (row) {
        ids = row.id
      } else {
        ids = this.$refs.Table.selection
          .map(ele => ele.id).join(',')
      }
      let msg = ""
      if(row.status == 1){
        msg = "确认启用此条异常规则？";
      }
      else{
        msg = "确认停用此条异常规则？";
      }
      this.$confirm(msg, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(() => {
        return statusErpFormula({id:row.id,status:status})
      }).then(() => {
         this.getList()
      }).catch(err=>{

      })
    },

    queryParamsChange({ factoryDeptCode, workshopCode,lineCode,lineId }) {
      this.queryParams = {
        factoryDeptCode,
        workshopCode,
        erpProductionLineCode:lineCode,
        lineId,
        status:this.queryParams.status,
        searchValue:this.queryParams.searchValue
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        factoryDeptCode: null,
        workshopCode: null,
        erpProductionLineCode: null,
        lineId:null,
        status:null,
        searchValue:null
      },
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      if (selection.length > 1) {
        this.single = false;
      } else if (selection.length == 1) {
        this.single = true;
      } else {
        this.single = null;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportLoading = true;
      const param = {
        ...this.queryParams,
      };
      exportRule(param)
        .then((res) => {
          downloadFile(
            res.file,
            decodeURIComponent(res.name) ||
              `异常/预警规则${this.parseTime(new Date(), "{y}{m}{d}{h}{i}{s}")}.xlsx`
          );
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
  },

  updated() {
    if (this.$refs.Table && this.$refs.Table.doLayout) {
      this.$refs.Table.doLayout();
    }
  }
};
</script>
<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap:wrap;
  .operate{
    flex:1
  }
  ::v-deep .el-form-item__content{
    line-height: 0;
  }
}
.pagination-container {
  margin: 0;
}
.status-use{
  color: #88c446;
  font-weight: 600;
}
.status-stop{
  color: #D9001B;
  font-weight: 600;
}
</style>
